# -*- coding: utf-8 -*-
from scpy.logger import get_logger
import os
import sys
import tornado
from tornado.web import HTTPError
from util.pgutil import PgUtil
import datetime
import json

reload(sys)
sys.setdefaultencoding('utf-8')

logger = get_logger(__file__)

CURRENT_PATH = os.path.dirname(__file__)
if CURRENT_PATH:
    CURRENT_PATH = CURRENT_PATH + "/"


pg = PgUtil()

class ChartHandler(tornado.web.RequestHandler):
    def get(self):
        # type_list =['法务', '新闻', '工商',\
        #             '失信', '执行', '招聘', '简历']
        # self.render('_chart.html',type_list=type_list)
        # self.render('_chart.html')
        self.render('_chart_search.html')

    def post(self):
        company_name = self.get_argument('companyName','')
        from_text = self.get_argument('from')
        to_text = self.get_argument('to')
        data = self.build_return_data(
            companyName=company_name,
            fromText=from_text,
            toText=to_text
        )

    def build_return_data(self, **kwargs):
        """

        :rtype : object
        """
        company_name = kwargs['companyName']
        from_text = kwargs['fromText']
        to_text = kwargs['toText']


class RecruitmentInfoHandler(tornado.web.RequestHandler):

    def get(self):
        data = self.build_return_data()
        if data:
            self.write(json.dumps(data, ensure_ascii=False, indent=4))
        else:
            raise HTTPError(404, 'not found.')

    def build_return_data(self):
        return_data = {}
        time_step_list = self.get_time_step()
        for time_step in time_step_list:
            _query = """
                    with a(category_type,count) as (select category_type, count(category_type) from recruitment where to_char(release_time,'YYYYMM')=%s group by category_type),
                    b(category_type) as (select distinct category_type from recruitment)
                    select b.category_type,
                    case
                    when a.count is null then 0
                    else
                    a.count
                    end
                    from b left join a on a.category_type=b.category_type
                    """
            _values = (time_step,)
            result = pg.select_all_sql(_query,_values)
            if result:
                return_data[time_step] = list()
                for item in result:
                    return_data[time_step].append({
                        'name': item[0],
                        'value': item[1]
                    })
            else:
                continue
        return return_data


    def get_time_step(self):
        time_step_list = list()
        begin_time = datetime.datetime.strptime('2013-08-31','%Y-%m-%d')
        end_time = datetime.datetime.now()
        time_delta = datetime.timedelta(days=30)
        while end_time>begin_time:
            time_step_list.append(end_time.strftime("%Y%m"))
            end_time -= time_delta
        if end_time.month == begin_time.month:
            time_step_list.append(begin_time.strftime("%Y%m"))
        return time_step_list

class CompanyChartHandler(tornado.web.RequestHandler):

    def get(self):
        company_name = self.get_argument('companyName', '')

        data = self.build_return_data(companyName=company_name)
        if data:
            self.write(json.dumps(data, ensure_ascii=False, indent=4))
        else:
            raise HTTPError(404, 'not found.')

    def build_return_data(self,**kwargs):
        return_data = {}
        company_name = kwargs['companyName']
        time_step_list = self.get_time_step()
        for time_step in time_step_list:
            return_data[time_step] = {}
            # category type dis
            return_data[time_step]['categoryTypeDis'] = []
            _query = """
                    with a(category_type,count) as (select category_type, count(category_type) from recruitment where to_char(release_time,'YYYYMM')=%s and company_name=%s
                    group by category_type),
                    b(category_type) as (select distinct category_type from recruitment)
                    select b.category_type,
                    case
                    when a.count is null then 0
                    else
                    a.count
                    end
                    from b left join a on a.category_type=b.category_type
                    """
            _values = (time_step,company_name)
            result = pg.select_all_sql(_query,_values)
            if result:
                return_data[time_step]['categoryTypeDis'] = list()
                for item in result:
                    return_data[time_step]['categoryTypeDis'].append({
                        'name': item[0],
                        'value': item[1]
                    })
            else:
                continue

            # similar company salary avg
            _query = """
                      SELECT AVG(salary) FROM recruitment WHERE company_name IN
                      (SELECT b.company_name FROM recruitment_monitor_company a,
                      recruitment_monitor_company b WHERE a.company_name=%s AND
                      a.scale = b.scale AND a.location = b.location AND
                      b.industry &&a.industry
                      GROUP BY b.company_name) AND to_char(release_time,'YYYYMM')=%s
                     """
            _values = (company_name,time_step)
            result = pg.select_sql(_query, _values)
            if result and result[0]:
                return_data[time_step]['similarCompanyAvgSalary'] = result[0]
            else:
                return_data[time_step]['similarCompanyAvgSalary'] = 0

            # company salary avg
            _query = """
                     select avg(salary) from recruitment where company_name=%s and
                     to_char(release_time,'YYYYMM')=%s
                     """
            _values = (company_name,time_step)
            result = pg.select_sql(_query,_values)
            if result and result[0]:
                return_data[time_step]['companyAvgSalary'] = result[0]
            else:
                return_data[time_step]['companyAvgSalary'] = 0
        return return_data


    def get_time_step(self):
        time_step_list = list()
        begin_time = datetime.datetime.strptime('2013-08-31','%Y-%m-%d')
        end_time = datetime.datetime.now()
        time_delta = datetime.timedelta(days=30)
        while end_time>begin_time:
            time_step_list.append(end_time.strftime("%Y%m"))
            end_time -= time_delta
        if end_time.month == begin_time.month:
            time_step_list.append(begin_time.strftime("%Y%m"))
        return time_step_list


class CategoryChartHandler(tornado.web.RequestHandler):

    def get(self):
        # data = self.build_return_data()
        with open('/home/scdev/cc_git/crawler-recruitment/webui/static/static/category.json') as f:
            data = json.loads(f.read())
        if data:
            self.set_header('Content-Type', 'application/json')
            self.write(data)
        else:
            raise HTTPError(404, 'not found.')

    def build_return_data(self,**kwargs):
        return_data = {}
        time_step_list = self.get_time_step()
        for time_step in time_step_list:
            return_data[time_step] = {}

            # category dis
            _query = """
                    with a(category_type,count) as (select category_type, count(category_type) from recruitment where to_char(release_time,'YYYYMM')=%s
                    group by category_type),
                    b(category_type) as (select distinct category_type from recruitment)
                    select b.category_type,
                    case
                    when a.count is null then 0
                    else
                    a.count
                    end
                    from b left join a on a.category_type=b.category_type
                     """
            _values = [time_step]
            result = pg.select_all_sql(_query, _values)
            if result:
                return_data[time_step]['categoryTypeDis'] = list()
                totalCount = 0
                for item in result:
                    return_data[time_step]['categoryTypeDis'].append({
                        'name': item[0],
                        'value': item[1]
                    })
                    totalCount += item[1]
                return_data[time_step]['categoryTypeCount'] = totalCount
            else:
                return_data[time_step]['categoryTypeDis'] = []
                return_data[time_step]['categoryTypeCount'] = 0
        return return_data


    def get_time_step(self):
        time_step_list = list()
        begin_time = datetime.datetime.strptime('2013-08-31','%Y-%m-%d')
        end_time = datetime.datetime.now()
        time_delta = datetime.timedelta(days=30)
        while end_time>begin_time:
            time_step_list.append(end_time.strftime("%Y%m"))
            end_time -= time_delta
        if end_time.month == begin_time.month:
            time_step_list.append(begin_time.strftime("%Y%m"))
        return time_step_list

if __name__ == '__main__':
    pass
